<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="考试/练习名称" prop="examName">
        <el-input
          v-model="queryParams.examName"
          placeholder="请输入考试/练习名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建者" prop="createdBySchoolUserId">
        <el-input
          v-model="queryParams.createdBySchoolUserId"
          placeholder="请输入创建者"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['Teacher:exams:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['Teacher:exams:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['Teacher:exams:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['Teacher:exams:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="examsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="考试/练习名称" align="center" prop="examName" />
      <el-table-column label="类型: 考试, 练习" align="center" prop="examType" />
      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="时长" align="center" prop="durationMinutes" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
              type="primary"
              @click="handleStartTask(scope.row)"
          >
            开始练习
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改考试练习任务对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="examsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属学校ID" prop="schoolId">
          <el-input v-model="form.schoolId" placeholder="请输入所属学校ID" />
        </el-form-item>
        <el-form-item label="实验场景ID" prop="scenarioId">
          <el-input v-model="form.scenarioId" placeholder="请输入实验场景ID" />
        </el-form-item>
        <el-form-item label="所属机房ID" prop="labId">
          <el-input v-model="form.labId" placeholder="请输入所属机房ID" />
        </el-form-item>
        <el-form-item label="考试/练习名称" prop="examName">
          <el-input v-model="form.examName" placeholder="请输入考试/练习名称" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable
            v-model="form.startTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker clearable
            v-model="form.endTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="设定时长" prop="durationMinutes">
          <el-input v-model="form.durationMinutes" placeholder="请输入设定时长" />
        </el-form-item>
        <el-form-item label="创建者" prop="createdBySchoolUserId">
          <el-input v-model="form.createdBySchoolUserId" placeholder="请输入创建者" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Exams">
import {
  listExams,
  getExams,
  delExams,
  addExams,
  updateExams,
  checkLabIdExists,
  checkSchoolIdExists
} from "@/api/Teacher/exams"
import {useExampleStore} from "@/stores/exampleStore.js";

const { proxy } = getCurrentInstance()

const examsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    schoolId: null,
    scenarioId: null,
    labId: null,
    examName: null,
    examType: null,
    startTime: null,
    endTime: null,
    durationMinutes: null,
    status: null,
    parameters: null,
    createdBySchoolUserId: null
  },
  rules: {
    schoolId: [
      { required: true, message: "所属学校ID不能为空", trigger: "blur" }
    ],
    scenarioId: [
      { required: true, message: "实验场景ID不能为空", trigger: "blur" }
    ],
    examName: [
      { required: true, message: "考试/练习名称不能为空", trigger: "blur" }
    ],
    examType: [
      { required: true, message: "类型: 考试, 练习不能为空", trigger: "change" }
    ],
    startTime: [
      { required: true, message: "开始时间不能为空", trigger: "blur" }
    ],
    endTime: [
      { required: true, message: "结束时间不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态: 已安排, 进行中, 已完成, 已取消不能为空", trigger: "change" }
    ],
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)
const exampleStore = useExampleStore();
const school = exampleStore.getSchool; // 直接从 Pinia 取
/** 查询考试练习任务列表 */
function getList() {
  loading.value = true
  queryParams.value.schoolId = school // 假设school对象有id属性
  console.log("查询参数", queryParams.value)
  listExams(queryParams.value).then(response => {
    examsList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

const handleStartTask = (row) => {
  window.location.href = "myapp://test";
  router.push('/page')
}


// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    examId: null,
    schoolId: null,
    scenarioId: null,
    labId: null,
    examName: null,
    examType: null,
    startTime: null,
    endTime: null,
    durationMinutes: null,
    status: null,
    parameters: null,
    createTime: null,
    createdBySchoolUserId: null
  }
  proxy.resetForm("examsRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.examId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加考试练习任务"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _examId = row.examId || ids.value
  getExams(_examId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改考试练习任务"
  })
}

/** 提交按钮 */
async function submitForm() {
  try {
    // 1. 表单基础验证
    const valid = await proxy.$refs.examsRef.validate();
    if (!valid) return;

    // 2. 并行验证机房ID和学校ID（提高效率）
    const validations = [];

    if (form.value.labId) {
      validations.push(
          checkLabIdExists(form.value.labId).catch(error => {
            return { code: 500, msg: "机房验证异常或学校验证异常" };
          })
      );
    }

    if (form.value.schoolId) {
      validations.push(
          checkSchoolIdExists(form.value.schoolId).catch(error => {
            return { code: 500, msg: "机房验证异常或学校验证异常" };
          })
      );
    }

    // 等待所有验证完成
    const results = await Promise.all(validations);

    // 3. 检查验证结果
    for (const res of results) {
      if (res.code !== 200) {
        proxy.$modal.msgError(res.msg || "ID验证失败");
        return;
      }
      if (res.data === 0) { // 假设返回data=0表示不存在
        proxy.$modal.msgError(res.msg || "该ID不存在");
        return;
      }
    }

    // 4. 执行新增/修改操作
    const apiFunc = form.value.examId != null ? updateExams : addExams;
    await apiFunc(form.value);

    proxy.$modal.msgSuccess(form.value.examId != null ? "修改成功" : "新增成功");
    open.value = false;
    getList();

  } catch (error) {
    console.error("提交出错:", error);
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _examIds = row.examId || ids.value
  proxy.$modal.confirm('是否确认删除考试练习任务编号为"' + _examIds + '"的数据项？').then(function() {
    return delExams(_examIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('Teacher/exams/export', {
    ...queryParams.value
  }, `exams_${new Date().getTime()}.xlsx`)
}

getList()
</script>
